const pageHelper = require('../../../../helpers/page_helper.js');
const dataHelper = require('../../../../helpers/data_helper.js');
// 引入MobX相关
const { storeBindingsBehavior } = require('../../../../miniprogram_npm/mobx-miniprogram-bindings/index');
const { observable } = require('../../../../miniprogram_npm/mobx-miniprogram/index');

// 创建本地store
const formSetStore = observable({
	// 当前表单状态
	formState: [],
	
	// 操作历史记录（用于撤销功能）
	fieldHistory: [],
	
	// 历史记录最大长度
	maxHistoryLength: 10,
	
	// 保存表单状态
	saveFormState(fields) {
		if (!fields) return;
		this.formState = JSON.parse(JSON.stringify(fields));
	},
	
	// 添加当前状态到历史记录
	addToHistory(fields) {
		if (!fields) return;
		
		// 深拷贝以确保历史状态不会被修改
		const historyCopy = JSON.parse(JSON.stringify(fields));
		
		// 添加到历史记录开头
		this.fieldHistory.unshift(historyCopy);
		
		// 限制历史记录长度
		if (this.fieldHistory.length > this.maxHistoryLength) {
			this.fieldHistory.pop();
		}
	},
	
	// 从历史记录恢复状态
	restoreFromHistory() {
		if (this.fieldHistory.length === 0) {
			return null;
		}
		
		// 取出最近的历史记录
		const lastState = this.fieldHistory.shift();
		
		// 更新当前状态
		this.formState = lastState;
		
		return lastState;
	},
	
	// 清空历史记录
	clearHistory() {
		this.fieldHistory = [];
	}
});

Component({
	behaviors: [storeBindingsBehavior],
	
	storeBindings: {
		store: formSetStore,
		fields: ['formState', 'fieldHistory'],
		actions: ['saveFormState', 'addToHistory', 'restoreFromHistory']
	},
	
	options: {
		addGlobalClass: true
	},

	/**
	 * 组件的属性列表
	 */
	properties: {
		fields: {
			type: Array,
			value: [],
			observer: function(newVal) {
				if (newVal && newVal.length > 0) {
					// 保存表单状态到MobX store
					this.saveFormState(newVal);
				}
			}
		},
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		cur: -1,
	},

	/**
	 * 生命周期方法
	 */
	lifetimes: {
		attached: function () {

		},

		ready: function () {
			// 检查是否有保存的表单状态
			if (this.data.formState && this.data.formState.length > 0) {
				this.setData({
					fields: this.data.formState
				});
				this.triggerEvent('formset', this.data.formState);
			}
		},

		detached: function () {
			// 在组件实例被从页面节点树移除时执行
			// 清理MobX绑定
			if (this.storeBindings) {
				this.storeBindings.destroyStoreBindings();
			}
		},
	},

	/**
	 * 组件的方法列表
	 */
	methods: {
		setGlow(cur) {
			this.setData({
				cur
			});
			setTimeout(() => {
				this.setData({
					cur: -1
				});
			}, 800);
		},

		url: function (e) {
			pageHelper.url(e, this);
		},

		set: function (fields) {
			this.setData({
				fields
			});
			// 保存到MobX store
			this.saveFormState(fields);
			this.triggerEvent('formset', fields);
		},

		get: function () {
			return this.data.fields;
		},

		bindEditTap: function (e) {
			let idx = pageHelper.dataset(e, 'idx');
			let edit = pageHelper.dataset(e, 'edit'); 
			if (!edit) {
				return pageHelper.showNoneToast('该字段不可编辑和删除');
			}
			wx.navigateTo({
				url: '/cmpts/public/form/form_set/field/form_set_field?idx=' + idx,
			});
		},
		
		bindUpTap: function (e) {
			let idx = pageHelper.dataset(e, 'idx');
			let fields = this.data.fields;
			
			// 保存到历史记录
			this.addToHistory(fields);
			
			dataHelper.arraySwap(fields, idx, idx - 1);
			this.setData({
				fields
			});
			this.setGlow(idx - 1);
			
			// 保存更新后的状态
			this.saveFormState(fields);
			this.triggerEvent('formset', fields);
		},

		bindDownTap: function (e) {
			let idx = pageHelper.dataset(e, 'idx');
			let fields = this.data.fields;
			
			// 保存到历史记录
			this.addToHistory(fields);
			
			dataHelper.arraySwap(fields, idx, idx + 1);
			this.setData({
				fields
			});
			this.setGlow(idx + 1);
			
			// 保存更新后的状态
			this.saveFormState(fields);
			this.triggerEvent('formset', fields);
		},
		
		// 撤销上一次操作
		undoOperation: function() {
			const lastState = this.restoreFromHistory();
			if (lastState) {
				this.setData({
					fields: lastState
				});
				this.triggerEvent('formset', lastState);
			} else {
				pageHelper.showNoneToast('没有可撤销的操作');
			}
		}
	}
})